<template>
  <XenListPage
    title="用人申请"
    :dataList="staffNeedList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选用人申请信息"
    emptyText="暂无用人申请信息"
    emptyDesc="暂无数据"
    detailPagePath="/subpkg-hr-syshrstaffneedrequestbill/details"
    permission-module="syshrstaffneedrequestbill"
    :showAddButton="false"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrStaffNeedRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type {
  ISysHrStaffNeedRequestBillView,
  ISysHrStaffNeedRequestBillQuery,
  ISysHrStaffNeedRequestBillEntryView,
} from "./api/interface";

// 创建API实例
const api = SysHrStaffNeedRequestBillApi();
const commonApiInstance = commonApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段
const visibleFields = [
  {
    key: "OrgName",
    label: "公司",
    formatter: (value: any) => value || "",
  },
  {
    key: "GroupName",
    label: "所属部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "StaffNeedRequestBillName",
    label: "单据编号",
    formatter: (value: any) => value || "",
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => value || "",
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "WorkflowStatus",
    label: "状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "EntryJobPositionName",
    label: "需求岗位",
    formatter: (value: any) => value || "",
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "approver",
    label: "审批人",
    placeholder: "请输入审批人",
  },
  {
    key: "approvalTime",
    label: "审批时间",
    type: "daterange",
    placeholder: "请选择审批时间范围",
  },
  {
    key: "groupId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "workflowStatus",
    label: "状态",
    type: "selector",
    placeholder: "请选择状态",
    options: ["待提交", "提交中", "审核中", "已完成", "已取消"],
  },
];

// 定义操作按钮（只保留查看功能）
const actions = [
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 定义合并后的数据结构（参考招聘申请的实现）
interface IMergedStaffNeedRequestBill {
  ID: string;
  StaffNeedRequestBillName: string; // 用人申请单号（BillCode）
  GroupName: string; // 部门
  WorkflowStatus: string; // 审批状态
  BillStatus: string; // 单据状态
  Approver: string; // 审批人
  ApprovalTime: string; // 审批时间
  Remark: string; // 备注
  OrgName: string; // 公司
  PositionList: Array<{
    // 需求岗位列表
    JobPositionName: string;
    HireNumber: number;
  }>;
  // 添加您要求的字段
  EntryJobPositionName: string; // 合并后的岗位信息字符串
  EntryHireNumber: string; // 合并后的总人数字符串
}

// 用人需求申请列表数据（合并后）
const staffNeedList = ref<IMergedStaffNeedRequestBill[]>([]);

// 原始API数据（合并前）
const rawStaffNeedList = ref<ISysHrStaffNeedRequestBillView[]>([]);

// 部门数据缓存（用于名称和ID的转换）
const departmentDataCache = ref<any[]>([]);

// 优化后的合并用人申请数据函数 - 参考招聘申请实现
const mergeStaffNeedData = async (
  rawData: ISysHrStaffNeedRequestBillView[],
): Promise<IMergedStaffNeedRequestBill[]> => {
  const mergedMap = new Map<string, IMergedStaffNeedRequestBill>();

  // 第一步：创建基础数据映射
  for (const item of rawData) {
    const billName = item.BillCode || ""; // 使用BillCode作为用人申请单号

    if (!mergedMap.has(billName)) {
      mergedMap.set(billName, {
        ID: item.ID || "",
        StaffNeedRequestBillName: billName,
        GroupName: (item as any).GroupName || "",
        WorkflowStatus: String(item.WorkflowStatus || ""),
        BillStatus: String(item.BillStatus || ""),
        Approver: item.Approver || "",
        ApprovalTime: formatDateTime(item.ApprovalTime) || "",
        Remark: item.Remark || "",
        OrgName: (item as any).OrgName || "",
        PositionList: [],
        EntryJobPositionName: "",
        EntryHireNumber: "",
      });
    }
  }

  // 第二步：一次性获取所有明细数据
  try {
    // 收集所有的用人申请单ID
    const billIds = Array.from(mergedMap.values())
      .map((item) => item.ID)
      .filter((id) => id);

    if (billIds.length === 0) {
      return Array.from(mergedMap.values());
    }

    // 一次性获取所有明细数据（完全按照招聘申请的逻辑）
    const allDetailsResponse = await api.searchList({
      Limit: 9999,
      Page: 1,
    });

    if (allDetailsResponse && allDetailsResponse.Data) {
      // 按用人申请单ID分组明细数据
      const detailsByBillId = new Map<
        string,
        ISysHrStaffNeedRequestBillEntryView[]
      >();

      allDetailsResponse.Data.forEach(
        (detail: ISysHrStaffNeedRequestBillEntryView) => {
          console.log("处理明细记录:", detail);
          // 完全按照招聘申请的逻辑：通过BillName找到对应的申请单
          const billName = (detail as any).HrStaffNeedName || "";
          const mergedItem = mergedMap.get(billName);
          console.log(
            `明细记录的 HrStaffNeedName: ${billName}，找到对应的申请单:`,
            mergedItem,
          );

          if (mergedItem) {
            if (!detailsByBillId.has(mergedItem.ID)) {
              detailsByBillId.set(mergedItem.ID, []);
            }
            detailsByBillId.get(mergedItem.ID)?.push(detail);
            console.log(
              `明细记录已添加到申请单 ${billName} (ID: ${mergedItem.ID})`,
            );
          } else {
            console.log(`未找到对应的申请单，HrStaffNeedName: ${billName}`);
          }
        },
      );

      console.log("明细数据分组结果:", detailsByBillId);

      // 为每个用人申请单合并岗位信息
      for (const [billName, mergedItem] of mergedMap.entries()) {
        const details = detailsByBillId.get(mergedItem.ID) || [];
        console.log(
          `处理申请单 ${billName} (ID: ${mergedItem.ID})，找到 ${details.length} 条明细:`,
          details,
        );

        const positionMap = new Map<string, number>();

        // 合并相同岗位的需求人数
        details.forEach((detail: ISysHrStaffNeedRequestBillEntryView) => {
          const positionName = detail.JobPositionName || "";
          const count = detail.HireNumber || 0;
          console.log(`处理明细: 岗位=${positionName}, 人数=${count}`);

          if (positionMap.has(positionName)) {
            positionMap.set(
              positionName,
              positionMap.get(positionName)! + count,
            );
          } else {
            positionMap.set(positionName, count);
          }
        });

        console.log(`申请单 ${billName} 岗位汇总:`, positionMap);

        // 转换为数组格式
        mergedItem.PositionList = Array.from(positionMap.entries()).map(
          ([jobPositionName, hireNumber]) => ({
            JobPositionName: jobPositionName,
            HireNumber: hireNumber,
          }),
        );

        // 生成合并后的字段
        let totalHireNumber = 0;
        const positionInfos = mergedItem.PositionList.map((pos) => {
          totalHireNumber += pos.HireNumber;
          return `${pos.JobPositionName}（${pos.HireNumber}人）`;
        });

        mergedItem.EntryJobPositionName = positionInfos.join("");
        mergedItem.EntryHireNumber = totalHireNumber.toString();

        console.log(
          `申请单 ${billName} 最终结果: EntryJobPositionName="${mergedItem.EntryJobPositionName}", EntryHireNumber="${mergedItem.EntryHireNumber}"`,
        );
      }
    }
  } catch (error) {
    console.error("获取明细数据失败:", error);
    // 如果获取明细失败，所有项目的PositionList保持为空数组
    for (const mergedItem of mergedMap.values()) {
      mergedItem.PositionList = [];
      mergedItem.EntryJobPositionName = "";
      mergedItem.EntryHireNumber = "0";
    }
  }

  return Array.from(mergedMap.values());
};

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysHrStaffNeedRequestBillQuery = {
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    };

    // 根据筛选参数构建查询对象
    if (filterParams.approver) {
      queryParams.Approver = filterParams.approver;
    }
    // 处理审批时间范围：确保结束日期包含当天的所有时间
    const approvalTimeRange = processDateRangeField(
      filterParams,
      "approvalTime",
    );
    if (approvalTimeRange) {
      queryParams.ApprovalTime = approvalTimeRange;
    }
    if (filterParams.groupId) {
      // XenDepartmentPicker组件直接返回部门ID
      queryParams.GroupId = filterParams.groupId;
    }
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.billStatus) {
      queryParams.BillStatus = filterParams.billStatus;
    }
    if (filterParams.workflowStatus) {
      queryParams.WorkflowStatus = filterParams.workflowStatus;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      rawStaffNeedList.value = response.Data;
      // 合并数据
      staffNeedList.value = await mergeStaffNeedData(response.Data);
    } else {
      rawStaffNeedList.value = [];
      staffNeedList.value = [];
    }
  } catch (error) {
    staffNeedList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });

  if (response && response.Data) {
    return await mergeStaffNeedData(response.Data);
  }

  return [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: IMergedStaffNeedRequestBill[]) => {
  staffNeedList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (staffNeedList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    });

    if (response && response.Data) {
      rawStaffNeedList.value = response.Data;
      // 合并数据
      staffNeedList.value = await mergeStaffNeedData(response.Data);
    } else {
      rawStaffNeedList.value = [];
      staffNeedList.value = [];
    }
  } catch (error) {
    staffNeedList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取用人申请信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    const response = await commonApiInstance.GetParentsTree();
    if (response && Array.isArray(response)) {
      // 缓存部门数据
      departmentDataCache.value = response;

      // 找到部门筛选字段并更新其部门数据
      const departmentField = filterFields.find(
        (field) => field.key === "groupId",
      );
      if (departmentField) {
        departmentField.departmentData = response;
      }
    }
  } catch (error) {
    console.error("加载部门数据失败:", error);
  }
};

// 页面加载
onMounted(async () => {
  await loadDepartmentData();
  fetchData();
});
</script>
